<?php

/**
 * @author chenxuezhi
 * @copyright 2016
 */

namespace Hrdgame\Controller;
use Common\Controller\ApiController;

class IndexController extends ApiController {
    
    public function login()
    {
        $appId = C('APPID');
        $appSecret = C('APPSECRET');
        $code = I('code','','string');
        
        $nickname = I('nickname','','string');
        $avatar = I('avatar','','string');

        if(!$code){
            $jsons['errno'] = 1;
            $jsons['msg'] = 'code不能为空';
            $this->ajaxReturn($jsons);
        }else if(empty($nickname)){
            $jsons['errno'] = 2;
            $jsons['msg'] = '昵称不能为空';
            $this->ajaxReturn($jsons);
        }else if(empty($avatar)){
            $jsons['errno'] = 2;
            $jsons['msg'] = '头像不能为空';
            $this->ajaxReturn($jsons);
        }
        
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code";

        $opts['http'] = array('method'=>'GET', 'timeout'=>5); // 设置超时
        $data = @file_get_contents($url, false, stream_context_create($opts));
        
        if($data) {
            $json = json_decode($data, true);
            $userId = isset($json['openid']) ? $json['openid'] : 0;
            
            if($userId){
                $map['userid'] = $userId;
                if(!$users = M('users')->where($map)->find()){
                    M('users')->add(array(
                        'userid'=>$userId,
                        'nickname'=>$nickname,
                        'avatar'=>$avatar,
                        'create_time'=>date('Y-m-d H:i:s')
                    ));
                }else if($users['nickname'] != $nickname || $users['avatar'] != $avatar){
                    M('users')->where($map)->save(array(
                        'nickname'=>$nickname,
                        'avatar'=>$avatar
                    ));
                }else{
                    $data = json_decode($data,true);
                    $data = array_merge($data, $users);
                }
            }
        }
        
        $this->ajaxReturn($data);
    }
    
    // 创建房间
    public function createRoom()
    {
        // 文件锁
        $lock = false;
        
        $userId = I('userId','','string'); // openid
        $gameType = I('gametype',0,'int'); // 游戏类型
        $roomName = I('roomName','','string'); // 房主名称
        $roomAvatar = I('roomAvatar','','string'); // 房主头像
        
        // 游戏时间
        $gameTime = array(
            1=>30,
            2=>40,
            3=>50
        );
        
        // 插入房间
        $data['state'] = 1; // 游戏中
        $data['player_id'] = $userId; // 房主openid
        $data['game_type'] = $gameType; // 游戏类型
        $data['game_time'] = isset($gameTime[$gameType]) ? $gameTime[$gameType] : 0; // 比赛时间s
        $data['room_name'] = $roomName; // 房主昵称
        $data['room_avatar'] = $roomAvatar; // 房主头像
        $data['create_time'] =  date('Y-m-d H:i:s'); // 创建时间
        if($data['room_id'] = M('fight_info')->add($data)) {
            $jsons['error'] = 0;
            $jsons['result'] = $data;
        }else{
            $jsons['error'] = 1;
        }
        $this->ajaxReturn($jsons);
    }
    
    // 向房间推送消息
    public function pushMsg()
    {
        $roomId = I('roomId',0,'int');
        $state = I('state',1,'int'); // 1好友加入, 2开始游戏, 3放弃游戏, 4同步游戏界面
        $msg = I('msg','','string');
        $plus = I('plus','','string');
        
        $contents['roomId'] = $roomId;
        $contents['state'] = $state;
        $contents['msg'] = $msg;
        $contents['plus'] = $plus;
        $jsons['state'] = $this->sendMsg($contents);
        $this->ajaxReturn($jsons);
    }
    
    // 好友进入
    public function friendIn()
    {
        $userId = I('userId','','string'); // 好友openid
        $roomId = I('gameRoomId',0,'int'); // 房间id
        
        $data = array();
        
        if($fight = M('fight_info')->where("id = '$roomId' and state = 1")->find()) { // 查询房间是否等待中
            
            // 更新好友openid
            $data['guest_player_id'] = $userId; // 好友openid
            $data['state'] = 2; // 游戏进行中(锁定房间)
            M('fight_info')->where("id = '$roomId'")->save($data);
            
            $data['roomId'] = $roomId;
            $data['player_id'] = $fight['player_id']; // 房子openid
            $data['waiting_inner'] = '等待发起者开始。。。';
            $data['room_name'] = $fight['room_name']; // 房主昵称
            $data['room_avatar'] = $fight['room_avatar']; // 房主头像
            $data['is_owner'] = ($userId == $fight['player_id']) ? true : false; // 是否是房主  
            
            // 推送消息至房间
            /*$contents['roomId'] = $roomId;
            $contents['state'] = 1; // 1好友加入, 2开始游戏, 3放弃游戏
            $contents['msg'] = '好友加入';
            $contents['friends'] = array(
                'is_owner'=>($userId == $fight['player_id']) ? true : false,
                'nickname'=>I('nickname','','string'),
                'avatar'=>I('avatar','','string')
            );
            
            $data['msg'] = $this->sendMsg($contents);*/
            $jsons['errno'] = 0;
            $jsons['result'] = $data;
            $this->ajaxReturn($jsons);
        }else{
           $jsons['errno'] = 1;
           $jsons['msg'] = '';
           $jsons['result'] = array();
           $this->ajaxReturn($jsons);
        }
    }
    
    public function test()
    {
        $room_id = $_REQUEST['room_id'];
        
        echo $room_id;
        // 建立socket连接到内部推送端口
        $client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 0);
        // 推送的数据，包含uid字段，表示是给这个uid推送
        $contents = array('roomId'=>$room_id, 'order_sn'=>123);
        // 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite($client, json_encode($contents)."\n");
        // 读取推送结果
        echo fread($client, 8192);
    }
    
    public function websockt()
    {
        $client = new \Org\Net\WebSocket();
		$client->connect('127.0.0.1', 8484, '/');
        
		$payload = json_encode(array(
			'code' => 'xxx',
			'id' => '1'
		));
		$rs = $client->sendData($payload);
	
		if( $rs !== true ){
			echo "sendData error...\n";
		}else{
			echo "ok\n";
		}
    }
    
    public function redis()
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);       
        $redis->set('lock',"123");
        
        echo $redis->get('lock');
    }
    
    
    // 推送成绩
    public function pushGrade()
    {
        $roomId = I('roomId',0,'int'); // 房间id
        $userId = I('userId','','string'); // 用户openid
        $gameType = I('gameType',0,'int'); // 游戏类型
        $playTime = I('playTime',0,'int'); // 游戏时间
        $gameTime = I('gameTime',0,'int'); // 比赛时间
        
        if(!$roomId){
            $jsons['errno'] = 1;
            $jsons['msg'] = '房间号不能为空';
            $this->ajaxReturn($jsons);
        }else if(!$userId){
            $jsons['errno'] = 2;
            $jsons['msg'] = '用户id不能为空';
            $this->ajaxReturn($jsons);
        }else{
            $data['room_id'] = $roomId; // 房间id
            $data['userid'] = $userId; // 用户openid
            $data['play_time'] = $playTime; // 玩的时间
            $data['game_type'] = $gameType; // 游戏类型
            $data['game_time'] = $gameTime; // 比赛时间
            $data['create_time'] = date('Y-m-d H:i:s'); // 创建时间
            
            // 记录用户最优成绩
            $map1['userid'] = $userId;
            if($ret = M('fight_top')->where($map1)->find()){
                if($ret['play_time'] > $playTime){
                    M('fight_top')->where($map1)->save($data); 
                }
            }else{
               M('fight_top')->add($data); 
            }
             
            $map2['room_id'] = $roomId;
            $ret = M('fight_grade')->where($map2)->find();
            
            // 如果房间有成绩，则直接返回false
            if($ret){ 
                $data['win_state'] = false;
            }else{
                
                // 开启事物
                $model = M();
                $model->startTrans();
                $ret1 = M('fight_grade')->add($data);
                
                $save['state'] = 3; // 游戏结束状态
                $save['win_id'] = $userId;
                $save['end_time'] = date('Y-m-d H:i:s');
                $ret2 = M('fight_info')->where("id = '$roomId'")->save($save);
                
                if($ret1 && $ret2){
                    $model->commit();
                    $data['win_state'] = true;
                }else{
                    $model->rollback();
                    $data['win_state'] = false;
                }
            }
            
            $jsons['errno'] = 0;
            $jsons['result'] = $data;
            $this->ajaxReturn($jsons);            
        }
    }
    
    // 好友排行榜
    public function friends_top()
    {
        $userid = I('userid','','string'); // 好友userid[世界排行不选]
        $gameType = I('gameType',1,'int'); // 游戏类型
        $page = I('page',1,'int'); //分页码
        $pageNum = I('pageNum',20,'int'); // 每页条数
        $offset = ($page - 1) * $pageNum;

        // 查询出用户好友
        if($userid) {
            $map['I.player_id'] = $userid;    
        }
        
        $map['I.game_type'] = $gameType;    
        $map['I.guest_player_id'] = array('NEQ','');
        $friends = M('fight_info')->alias('I')
            ->field('T.*,I.game_type as game_type')
            ->join('INNER JOIN c_fight_top T ON T.userid = I.guest_player_id')
            ->where($map)
            ->order('T.play_time asc')
            ->group('I.guest_player_id')
            ->limit($offset, $pageNum)
            ->select();
        
        $openids = array();
        $users = array(); 
        if($friends){
            foreach($friends as $item){
                $openids[] = $item['userid'];
            }
            
            $users = M('users')->where(array('userid'=>array('in',$openids)))->getField('userid,nickname,avatar');
            
            // 字段转换
            foreach($friends as &$items){
                $second = round($items['play_time'] / 1000); // 毫秒换算为秒
                $items['nickname'] = isset($users[$items['userid']]) ? $users[$items['userid']]['nickname'] : '';
                $items['avatar'] = isset($users[$items['userid']]) ? $users[$items['userid']]['avatar'] : '';
                $items['grade'] = $this->timeTograde($items['game_type'], $second);
                
                //$s = intval($items['play_time'] / 60) < 10 ? '0' . intval($items['play_time'] / 60) : intval($items['play_time'] / 60);
                //$m = intval($items['play_time'] % 60) < 10 ? '0' . intval($items['play_time'] % 60) : intval($items['play_time'] % 60);
                $items['play_str'] = $this->microtime_format($items['play_time']);
            }
        }
        
        $data['list'] = $friends;
        $jsons['errno'] = 0;
        $jsons['result'] = $data;
        $this->ajaxReturn($jsons);
    }
    
    private function microtime_format($millisecond)
    {
        $second = round($millisecond / 1000,2); // 秒
        $min = round($second / 60); // 分
        if($min < 10){
            $min = '0'.$min;
        }
        $second = $second - intval($second / 60) * 60;
        if($second < 10){
            $second = '0'.$second;
        }
        
        return $min.':'.$second;
    }    
    
    // 时间转换等级
    private function timeTograde($type, $s)
    {
        $gameType = array(1=>3, 2=>4, 3=>5);
        $gameType = isset($gameType[$type]) ? $gameType[$type] : 3;
        $range = $gameType * 5;
        
        if( (0 * $range) <= $s && $s <= (1 * $range) ){
            $srt = '太子太师';
        }elseif( (1 * $range) <= $s && $s <= (2 * $range) ){
            $srt = '尚书令';
        }elseif( (2 * $range) <= $s && $s <= (3 * $range) ){
            $srt = '光禄大夫';
        }elseif( (3 * $range) <= $s && $s <= (4 * $range) ){
            $srt = '中书令';
        }elseif( (4 * $range) <= $s && $s <= (5 * $range) ){
            $srt = '黄门侍郎';
        }elseif( (5 * $range) <= $s && $s <= (6 * $range) ){
            $srt = '尚书右丞';
        }elseif( (6 * $range) <= $s && $s <= (7 * $range) ){
            $srt = '国子博士';
        }elseif( (7 * $range) <= $s && $s <= (8 * $range) ){
            $srt = '太史令';
        }elseif( (8 * $range) <= $s && $s <= (9 * $range) ){
            $srt = '中州司马';
        }elseif( (9 * $range) <= $s && $s <= (10 * $range) ){
            $srt = '朝议郎';
        }elseif( (10 * $range) <= $s && $s <= (11 * $range) ){
            $srt = '儒林郎';
        }else{
            $srt = '将士郎';
        }
        return $srt;
    }
    
    // Socket发送数据
    private function sendMsg($contents)
    {
        // 建立socket连接到内部推送端口
        $client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 1);
        // 推送的数据，包含uid字段，表示是给这个uid推送
        
        // 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite($client, json_encode($contents)."\n");
        // 读取推送结果
        return fread($client, 8192);   
    }
}